package com.study.util;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.model.BatchStatus;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.study.config.QiniuConfigProperty;
import com.study.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class QiniuUtil {

    @Autowired
    private QiniuConfigProperty qiniuConfigProperty;

    public String getUploadToken(){
        Auth auth =getAuth();

        StringMap stringMap = new StringMap();
        stringMap.put("returnBody", "{\"fileKey\":\"$(key)\",\"name\":\"$(fname)\",\"url\":\""+qiniuConfigProperty.getDomain()+"/$(key)\",\"hash\":\"$(etag)\",\"bucket\":\"$(bucket)\",\"fileSize\":$(fsize)},\"uid\":$(x:uid)}");

        return auth.uploadToken(qiniuConfigProperty.getBucket(),null,3600,stringMap);
    }

    private Auth getAuth() {
        return Auth.create(qiniuConfigProperty.getAccessKey(),qiniuConfigProperty.getSecretKey());
    }

    public void batchDeleteFile(String[] keyList) {
        Configuration configuration = new Configuration(Region.region2());
        BucketManager bucketManager = new BucketManager(getAuth(), configuration);

        try {
            BucketManager.BatchOperations batchOperations = new BucketManager.BatchOperations();
            batchOperations.addDeleteOp(qiniuConfigProperty.getBucket(), keyList);
            bucketManager.batch(batchOperations);
        } catch (QiniuException e) {
            throw new ServiceException("七牛文件删除失败",e);
        }

    }
}
